<template>
    <div class="projectWrap">
        <div class="projectInner">
            <div class="p-title">
                <span class="close" @click="closeProjects">&times;</span>
                一个病人多项检查
            </div>
            <div class="p-content">
                <div class="p-left">
                    <div class="projectBox" v-for="(item,index) in box" @click.stop="swithcBoxIndex(index)">
                        <div class="removeIcon" @click="closeProject(index)">
                            <span>&times;</span>
                        </div>
                        <div class="input-wrap">
                            <em class="title"><em>*</em>输送类别：</em>
                            <div :class="['con pointer',boxIndex==index && showIndex ==1?'act':'']" id="classify" @click="selectTab(1)"><div>{{item.classifyname}}</div></div>
                        </div>
                        <div class="input-wrap">
                            <em class="title"><em>*</em>输送项目：</em>
                            <div :class="['con pointer',boxIndex==index && showIndex ==2?'act':'']"  @click="showCatalog(item.classifyid)"><div>{{item.catalogname}}</div></div>
                        </div>
                        <div class="input-wrap">
                            <em class="title"><em class="unvisible">*</em>目的地：</em>
                            <div class="clear-btn" v-show="item.endaddr != ''" @click="clearInputTxt(index)">&times;</div>
                            <div :id="'finish'+index" :class="['con pointer',boxIndex==index && showIndex ==3?'act':'']" @click="showFinish(index)"><div>{{item.endaddr}}</div></div>
                        </div>
                    </div>

                    <div class="input-wrap add">
                        <input @click="addProject" type="button" value="增加项目">
                    </div>

                    <div class="input-wrap">
                        <em class="title"><em>*</em>起点科室：</em>
                        <div id="start" :class="['con pointer',showIndex == 7 || showIndex == 8?'act':'']" @click="showRoom">
                            <div class="input-box">{{info.startaddr}}</div>
                        </div>
                    </div>
                    <div style="padding: 1px 0">
                        <div class="input-wrap">
                            <input type="button" @click="showStart" value="重设起点地址"/>
                        </div>
                    </div>

                    <div class="input-wrap" @click="showStartBad">
                        <em class="title"><em>*</em>起点床号：</em>
                        <div class="con">
                            <input id="startbed" type="text" class="name" v-model="info.startbed" @keypress.enter="tabAuto">
                        </div>
                    </div>
                    <div class="input-wrap">
                        <em class="title"><em>*</em>携带设备：</em>
                        <div :class="['con pointer',showIndex ==4?'act':'']" @click="showTackle"><div>{{info.tackle}}</div></div>
                    </div>
                    <div class="input-wrap">
                        <em class="title">备注：</em>
                        <div class="clear-btn" v-show="info.message != ''" @click="info.message = ''">&times;</div>
                        <div class="con"><input v-model="info.message" type="text" class="memo" ></div>
                    </div>
                    <div class="input-wrap" id="projectDate">
                        <em class="title">预约时间：</em>
                        <div class="clear-btn" v-show="info.appointment != ''" @click="cancelAppointmentTime">&times;</div>
                        <div class="pointer con" @click="showAppointmentTime"><div>{{info.appointment}}</div></div>
                        <date-time
                            :date="orderTime"
                            :option="orderOption"
                            :limit="limit"
                            class="calendar small"
                            @cancel="cancelAppointmentTime"
                            @change="setAppointmentTime"
                        ></date-time>
                    </div>

                    <div class="input-wrap fast">
                        <input :class='info.attribute == 3?"fastorder":""' @click="switchFastorder" type="button" value="急单">
                    </div>

                    <button @click="submit" class="btn">{{submitTxt}}</button>
                </div>
                <div class="p-right" v-if="showIndex!=3 && showIndex!=8">
                    <div class="select-handle" v-if="showIndex==9">
                        <div class="search-input">
                            <input type="text" placeholder="请输入床号或病人名称" v-model="searchPatient">
                        </div>
                    </div>

                    <div :class="['select-wrap',{'horizontal':isHorizontal,'hasSelect':showIndex==9}]">
                        <ul class="itemUl iconLi" v-if="showIndex==1">
                            <li class="itemLi" :key="item.id" v-for="item in classifyLis" v-if="item.title!='物流科'" @click="selectClassify(item.id,item.title)">
                                <img :src="item.src" alt="">
                                <span>{{item.title}}</span>
                            </li>
                        </ul>
                        <ul class="itemUl" v-if="showIndex==2">
                            <li class="itemLi" :key="item.id" v-for="item in catalogLis" @click="selectCatalog(item.id,item.title)">
                                <span>{{item.title}}</span>
                            </li>
                        </ul>
                        <ul class="itemUl" v-if="showIndex==7">
                            <li class="itemLi" v-for="item in roomLis" @click="selectStartRoom(item.name)">
                                <span>{{item.name}}</span>
                            </li>
                        </ul>
                        <!-- 病人列表 -->
                        <ul class="itemUl" v-if="showIndex==9">
                            <li class="itemLi" v-for="item in filteredPatient" @click="selectPatient(item)">
                                <span>{{item.Name}}{{item.BedNo == ''?'':' 床号:'+item.BedNo}}</span>
                            </li>
                        </ul>
                        <ul class="itemUl iconLi" v-if="showIndex==4">
                            <li :class="[item.isActive ? 'itemLi-active' : '', 'itemLi']" :key="item.id" v-for="item in tackleLis" @click="selectTackle(item.title)">
                                <img :src="item.src" alt="">
                                <span :style="{fontSize: item.title == '无' ? '19px' : '', marginTop: item.title == '无' ? '0' : ''}">{{item.title}}</span>
                            </li>
                        </ul>

                        <ul class="itemUl" v-if="showIndex==5">
                            <li class="itemLi" @click="submit">
                                <span>确定下单</span>
                            </li>
                        </ul>
                    </div>
                </div>

                <div class="p-right" v-if="showIndex==3 || showIndex==8">
                    <vue-cascader
                        :data="addrData"
                        :isMulti="isMulti"
                        :size="addrSize"
                        :backBtnText="btnText"
                        :backBtnStyles="backBtnStyles"
                        :backBtnHover="backBtnHover"
                        :backBtnPosi="backBtnPosi"
                        @callback="getFullName"
                    />
                </div>
            </div>
        </div>
        <div v-if="againSure" class="modal-bg"></div>
        <div v-if="againSure" class="patientModal">
            <div class="pHead">是否发送</div>
            <div class="pBody">
                <div class="pType">病人床号 {{info.startbed}}　的检查项目：</div>
                <div class="pCont">
                    <div class="pNum" v-for="(item,index) in box">
                        {{index+1}}、{{item.classifyname}} - {{item.catalogname}}
                    </div>
                </div>
            </div>
            <div class="pBottom">
                <button class="sure" @click="surePost">确认</button>
                <button class="cancel" @click="againSure=false">取消</button>
            </div>
        </div>
    </div>
</template>
<script>
    import dateTime from "../tips/calendar2.vue";
    import today from "../common/today";
    import {roomAlias} from '../common/com'
    import common from '../common/com'
    import {
        addressUrl,
        tackleUrl,
        catalogUrl,
        destinationUrl,
        submitUrl
    } from '../common/ajax'
    export default {
        data() {
            return {
                submitTxt:'确定下单',
                cid: '',
                box: [{classifyid:'',classifyname:'',catalogid:'',catalogname:'',endaddr:''}, {classifyid:'',classifyname:'',catalogid:'',catalogname:'',endaddr:''}],  // 初始时为两个
                info: {
                    attribute: 1,
                    message:'',
                    appointment:'',
                    tackle:'',
                    startbed:'',
                    finishbed:''
                },
                boxIndex: 0,
                isSubmit: true,
                catalogLis: [],
                finishLis: [],
                startLis: [],
                patientLis:[],
                roomalias:roomAlias.site_alias,
                tackleLis: [],
                showIndex: "",
                catalogId: "",
                patientRom:'',
                searchPatient:'',
                orderTime: {
                    time: ""
                },
                orderOption: {
                    type: "min",
                    week: ["一", "二", "三", "四", "五", "六", "日"],
                    month: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                    format: "YYYY-MM-DD HH:mm",
                    placeholder: "预约时间",
                    inputStyle: {
                        width: "0",
                        height: "0",
                        display: "none",
                    },
                    color: {
                        header: "#46bd9e",
                        headerText: "#fff"
                    },
                    buttons: {
                        ok: "确定",
                        cancel: "取消"
                    },
                    overlayOpacity: 0.5, // 0.5 as default
                    dismissible: true // as true as default
                },
                limit: [{
                    type: "fromto",
                    from: today.tmr(-1)
                }],
                againSure:false,
                // 地址选择
                addrData: [],
                addrSize: 'small',
                isMulti: false,
                btnText: '返回',
                backBtnStyles:{
                    background: '#ffd4c6',
                    color: '#fd2b2b'
                },
                backBtnHover:{
                    background: 'red',
                    color: '#fff'
                },
                backBtnPosi:'top',
                fullName: '',
                currIndex: '',  // 用于确认当前选择的地址是对应哪项检查
            };
        },
        props: {
            starts: "",
            classifyLis: {
                type: Array,
                default: () => []
            },
            roomLis:{
                type: Array,
                default: () => []
            },
            parentRoom:'',
            setBadStatus:'',
            isHorizontal:''
        },
        components: {
            "date-time": dateTime,
        },
        methods: {
            getFullName(item){
                let str = item.join(' ')
                if(this.showIndex == 3) this.box[this.currIndex].endaddr = str
                if(this.showIndex == 8) {
                    this.info.startaddr = str
                    this.showStart()    // 否则无法同步更新startaddr
                }
            },
            selectTab(index) {
                this.showIndex = index;
            },
            // 关闭整个弹窗
            closeProjects() {
                this.$emit("closeProjects");
            },
            addProject() {
                if(this.box.length < 5) {
                    this.box.push({classifyid:'',classifyname:'',catalogid:'',catalogname:'',endaddr:''});
                    this.boxIndex = this.box.length - 1;
                    this.selectTab(1);
                }
            },
            closeProject(index) {
                if(this.box.length > 1) {
                    this.box.splice(index, 1);
                }
            },
            loadNewAddress(){
                jQuery.ajax({
                    url: addressUrl,
                    type: 'get',
                    cache: false,
                    success: function(data){
                        if(data.success){
                            var newData = common.roomMerge(data.data, this.cid)
                            this.addrData = newData;
                        }else {
                            throwErrorTips('获取地址信息失败',data.msg)
                        }
                    }.bind(this)
                })
            },
            // 获取数据
            loadTackle() {
                jQuery.ajax({
                    url: tackleUrl,
                    type: "post",
                    dataType: "json",
                    cache: false,
                    success: function(data) {
                        if (data.success) {
                            this.tackleLis = data.data.lis.map(v => {
                                    Object.assign(v, {
                                        src: `/static/icon_tackle/${v.title}.png`
                                    });
                                return v;
                            })
                            if(this.info.tackle != ' '){
                                this.tackleLis.forEach(v => {
                                    this.$set(v, 'isActive', false)
                                })

                                let arr = this.info.tackle.split(' / ')
                                this.tackleLis.forEach(v => {
                                    arr.indexOf(v.title) != -1 ? v.isActive = true : v.isActive = false;
                                })
                            }
                        }else {
                            throwErrorTips('获取携带设置失败',data.msg)
                        }
                    }.bind(this)
                });
            },
            loadPatients(){
                this.patientLis = [];
                let pr = this.patientRom;
                for(var val of this.roomalias){
                    if(val.alias == this.patientRom){
                        let pra = [];
                        for(var room of val.room){
                            pra.push(room.name)
                        }
                        pr = pra.join(',')
                    }
                }
                let m = this.$root.$data.hisErrTips[this.$root.$data.cid] || ''
                jQuery.ajax({
                    url: this.$root.$data.lineUrl[this.$root.$data.cid],
                    type:'get',
                    dataType: 'json',
                    cache: false,
                    data:{ks:pr},
                    success: function(data) {
                        if(data.success){
                            let nlist = [];
                            if(data.data != '' && data.data != null && data.data.length > 0){
                                for(var val of data.data){
                                    val.BedNo = val.BedNo.substring(val.BedNo.length-3)
                                    nlist.push({BedNo:val.BedNo,Name:val.Name})
                                }
                            }else {
                                nlist = [];
                            }
                            this.patientLis = nlist.sort(function(a,b){
                                return a.BedNo - b.BedNo
                            });
                        }else {

                            throwErrorTips('获取病人列表失败',data.msg,m)
                        }
                    }.bind(this),
                    error:function(xhr){
                        throwErrorTips('获取病人列表失败',xhr.status,m)
                    }
                });
            },
            swithcBoxIndex(index) {
                this.boxIndex = index;
            },
            // 左侧选择项目
            showCatalog(classifyid) {
                if(classifyid != ''){
                    jQuery.ajax({
                        url: catalogUrl,
                        type: "post",
                        dataType: "json",
                        cache: false,
                        data: { classifyid: classifyid },
                        success: function(data) {
                            if (data.success) {
                                this.catalogLis = data.data.lis;
                                this.selectTab(2);
                            }else {
                                throwErrorTips('获取输送项目失败',data.msg)
                            }
                        }.bind(this)
                    });
                }
            },
            showFinish(index) {
                this.selectTab(3);
                this.currIndex = index;
                this.loadNewAddress();
            },
            showRoom(){
                this.selectTab(7);
            },
            showStart() {
                this.selectTab(8);
                this.loadNewAddress();
            },
            showStartBad(){
                if(this.cid ==28){
                    if(this.patientRom == ''){
                        this.$Message({type:'error',message:'请先选择起点科室'})
                        return
                    }
                    this.showIndex = 9
                }else {
                    this.showIndex = 0
                }
                setTimeout(function(){
                    jQuery("#startbed").focus();
                }.bind(this),20)
            },
            showTackle() {
                this.loadTackle();
                this.selectTab(4);
            },
            showAppointmentTime() {
                jQuery("#projectDate .cov-vue-date input").click();
            },
            setAppointmentTime(m) {
                this.info.attribute = 2;
                this.info.appointment = m;
            },
            cancelAppointmentTime(){
                this.info.appointment = '';
                this.info.attribute = 1;
            },
            // 右侧列表展示
            selectClassify(id, name) {
                this.box[this.boxIndex].classifyname = name;
                this.box[this.boxIndex].classifyid = id;
                this.box[this.boxIndex].catalogname = "";
                this.classifyId = id;
                this.showCatalog(id);
            },
            selectCatalog(id, name) {
                this.box[this.boxIndex].catalogname = name;
                this.box[this.boxIndex].catalogid = id;
                this.catalogId = id;
                //显示关联地址
                jQuery.ajax({
                    url: destinationUrl,
                    type: "post",
                    dataType: "json",
                    data: {
                        classifyid: this.box[this.boxIndex].classifyid,
                        catalogid: id },
                    cache: false,
                    success: function(data) {
                        if (data.success) {
                            setTimeout(function(){
                                if(data.data.end){
                                    this.box[this.boxIndex].endaddr = data.data.end;
                                }
                                this.tabAuto()
//              if(this.box[this.boxIndex].endaddr == ''){
//                  jQuery("#finish"+this.boxIndex).click();
//              }else {
//
//              }
                            }.bind(this),20)

                        }else {
                            throwErrorTips('获取关联地址失败',data.msg)
                        }
                    }.bind(this)
                });
            },
            selectStartRoom(name){
                sessionStorage.setItem('preRomm',name);
                let arr = this.starts.split(' ')
                if(arr.length > 2){
                    this.starts = arr[0] + ' '+arr[1]
                }
                this.info.startaddr = this.starts + ' '+ name ;
                this.patientRom = name;
                if(this.$root.$data.lineCid.indexOf(this.cid) != -1){
                    this.loadPatients()
                    this.showStartBad()
                }else {
                    this.tabAuto()
                }

            },
            selectPatient(val){
                let b = '';
                if(val.BedNo != ''){
                    b = ' '+ val.BedNo;
                }
                this.info.startbed = val.Name + b;
                this.tabAuto();
            },
            selectTackle(name) {
                if(this.info.tackle == '' || this.info.tackle == '无' || name == '无'){
                    this.info.tackle = name;
                    this.tackleLis.forEach(v => {
                        v.title == name ? v.isActive = true : v.isActive = false;
                })
                }else{
                    // 判断name是否已在tackleLis当中
                    if(this.info.tackle.indexOf(name) != -1){
                        let arr = this.info.tackle.split(' / ');
                        this.info.tackle = arr.filter(v => v != name).join(' / ')
                        this.tackleLis.forEach(v => {
                            if(v.title == name) v.isActive = false;
                    })
                    }else{
                        this.info.tackle += ` / ${name}`
                        this.tackleLis.forEach(v => {
                            if(v.title == name) v.isActive = true;
                    })
                    }
                }
                // this.info.tackle = name;
                // this.tabAuto();
            },
            switchFastorder() {
                if(this.info.attribute == 1){
                    this.info.attribute = 3;
                    return
                }
                if(this.info.attribute == 3){
                    this.info.attribute = 1;
                    return
                }
            },
            submitAjax(jsons,ind){
                jQuery.ajax({
                    url: submitUrl,
                    type:'post',
                    dataType: 'json',
                    cache: false,
                    data:{'data':jsons},
                    success: function(data) {
                        if(ind == this.box.length-1){
                            this.submitTxt='确定下单';
                            this.isSubmit=true;
                            this.closeProjects()
                        }
                        if(data.success){
                            if(ind == this.box.length-1){
                                this.closeProjects()
                                this.$Message({type:'success',message:'下单成功'})
                            }
                            if(!common.isEmptyObject(data.datat)){
                                let postjson = JSON.parse(jsons);
                                let socketJson = {};
                                socketJson['istobg'] = true;
                                socketJson['uid'] = '';
                                socketJson['type']='1';
                                socketJson['otype']='待分配';
                                socketJson['id'] = String(data.datat.id);
                                socketJson['sn'] = data.datat.sn;
                                socketJson['classify'] = postjson.classifyname;
                                socketJson['catalog'] = postjson.catalogname;
                                socketJson['site']= postjson.startaddr;
                                this.$emit('sendsocketfn',socketJson)
                            }
                        } else {
                            throwErrorTips('下单失败',data.msg)
                        }
                    }.bind(this),
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        this.closeProjects()
                        this.$Message({type:'error',message:'目前网络状况差，请刷新页面后重试，ERROR：'+xhr.statusText+',status：'+xhr.status})
                    }.bind(this),
                });
            },
            submit() {
                if(this.$root.$data.ssOffDuty){
                    this.$Message({type:'error',message:'输送调度不在服务时间内，请改用电话方式联系'});
                    return
                }
                //相同小类
                let hash = {};
                let hashs = {};
                let arrbox = this.box.reduce(function(item, next) {
                    (hashs[next.classifyid] && hash[next.catalogid]) ? '' :(hashs[next.classifyid] = true , hash[next.catalogid] = true , item.push(next))
                    return item
                }, []);
                let l = this.box.length - arrbox.length;
                if(  l > 0){
                    this.$Message({type:'error',message:'有相同的输送类型，请重新选择'})
                    return
                }
                for(var i = 0 ; i < this.box.length; i++ ){
                    let value = this.box[i];
                    this.boxIndex = i;
                    if(jQuery.trim(value.classifyid) == ''){
                        this.selectTab(1);
                        this.$Message({type:'error',message:'请选择输送类别'})
                        return
                    }
                    if(jQuery.trim(value.catalogid) == ''){
                        this.showCatalog(value.classifyid);
                        this.$Message({type:'error',message:'请选择输送项目'})
                        return
                    }
                    if(jQuery.trim(value.endaddr) == ''){
                        value.endaddr = '等科室医务人员确定';
                    }
                }

                if(this.patientRom == ''){
                    this.showRoom();
                    this.$Message({type:'error',message:'请选择输送起点科室'})
                    return
                }
                if(jQuery.trim(this.info.startbed) == ''){
                    if(this.setBadStatus){
                        this.showStartBad();
                        this.$Message({type:'error',message:'请填写床号，方便我们派送'})
                        return
                    }
                }
                if(jQuery.trim(this.info.tackle) == ''){
                    this.showTackle();
                    this.$Message({type:'error',message:'请选择输送设备'})
                    return
                }
                //预约时间比较
                if (this.orderTime.time != "") {
                    let setT = new Date(this.orderTime.time.replace(/-/g, "/"));
                    let nowT = new Date(
                        jQuery.ajax({ async: false }).getResponseHeader("Date")
                    );
                    let t = setT.getTime() - nowT.getTime();
                    if (t <= 0) {
                        this.$Message({type:'error',message:'预约时间必须大于现在的时间'})
                        return;
                    }else if(t >= 15*24*60*60*1000){
                        this.$Message({type:'error',message:'不能预约超15天'});
                        return
                    }
                }
                this.againSure = true;
            },
            surePost(){
                if(this.isSubmit){
                    this.isSubmit = false;
                    let timeStamp = new Date().getTime();
                    if(jQuery.trim(this.info.startbed) == ''){
                        this.info.startbed = '等医务人员待定'
                    }
                    for(var i = 0 ; i < this.box.length; i++ ){
                        let postJson = {};
                        let value = this.box[i];
                        let only = timeStamp + i
                        value['only'] = only.toString();
                        this.info.attribute = this.info.attribute.toString();
                        postJson = this.hpjson(value,this.info);
                        this.submitAjax(JSON.stringify(postJson),i)
                    }
                }

            },
            hpjson(jsonbject1,jsonbject2){
                var resultJsonObject={};
                for(var attr in jsonbject1){
                    resultJsonObject[attr]=jsonbject1[attr];
                }
                for(var attr in jsonbject2){
                    resultJsonObject[attr]=jsonbject2[attr];
                }
                return resultJsonObject;
            },
            clearInputTxt(index){
                this.box[index].endaddr = ''
            },
            tabAuto(){
                let _this = this;
                for(var i = 0 ; i < this.box.length; i++ ){
                    let value = this.box[i];
                    this.boxIndex = i;
                    if(jQuery.trim(value.classifyid) == ''){
                        _this.selectTab(1);
                        return
                    }
                    if(jQuery.trim(value.catalogid) == ''){
                        _this.showCatalog(value.classifyid);
                        return
                    }
                    if(jQuery.trim(value.endaddr) == ''){
                        jQuery("#finish"+i).click();
                        return
                    }
                }
                if(this.patientRom == ''){
                    this.showRoom();
                    return
                }
                if(jQuery.trim(this.info.startbed) == ''){
                    this.showStartBad();
                    return
                }
                if(jQuery.trim(this.info.tackle) == ''){
                    this.showTackle();
                    return
                }
                this.selectTab(5);
            }
        },
        computed: {
            filteredPatient: function () {
                var search = this.searchPatient;
                if (search) {
                    return this.patientLis.filter(function(product) {
                        return Object.keys(product).some(function(key) {
                            return String(product[key]).toLowerCase().indexOf(search) > -1
                        })
                    })
                }
                return this.patientLis;
            }
        },
        created() {
            this.loadNewAddress();
            this.info.startaddr = this.starts;
            this.cid = this.$root.$data.cid;
            this.patientRom = this.parentRoom;
            if(this.$root.$data.lineCid.indexOf(this.cid) != -1) {
                if(this.patientRom == ''){
                    this.showRoom();
                }else {
                    this.showStartBad();
                    this.loadPatients();
                }

            } else {
                if(this.patientRom == ''){
                    this.showRoom();
                }else {
                    this.selectTab(1);
                }

            }

        }
    };
</script>
<style scoped lang="less">
    @import "../assets/less/projects.less";
</style>
